package com.example.eventlistener.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.support.TaskUtils;

// 需要打开下面这个注解
// @Configuration
public class AsyncEventConfig {

    /**
     * 注意: 1. @Bean注解需要指定生成bean的名字, 因为Spring里面已经有个同名的bean, 如果不指定名字, 无法替换IOC中已有的Bean
     *       2. 这个配置是全局使能异步模式
     * @return ApplicationEventMulticaster
     */
    @Bean(name="applicationEventMulticaster")
    ApplicationEventMulticaster asyncMulticaster() {
        SimpleApplicationEventMulticaster applicationEventMulticaster = new SimpleApplicationEventMulticaster();
        applicationEventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
        applicationEventMulticaster.setErrorHandler(TaskUtils.LOG_AND_SUPPRESS_ERROR_HANDLER);
        return applicationEventMulticaster;
    }
}
